﻿using System.Threading.Tasks.Dataflow;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace test.XcoAppSpaces.Core.Ports
{
	[TestFixture, Explicit]
	internal class DataFlowTests
	{
		[Test]
		public void TestException()
		{
			TaskScheduler.UnobservedTaskException += (sender, args) => Console.WriteLine("unobserved exception!");
			var block = new ActionBlock<int>(m =>
				{
					Console.WriteLine("task " + m);
					throw new Exception("error " + m);
				});

			block.Post(123);
			block.Post(456); //this is not processed
			
			Thread.Sleep(500);

			Console.WriteLine("test " + block.Completion.Status); //completion status is faulted!
		}

		[Test]
		public void Choice()
		{
			var block1 = new BufferBlock<int>();
			var block2 = new BufferBlock<Exception>();

			Task.Factory.StartNew(() =>
				{
					Thread.Sleep(500);
					block2.Post(new Exception("some error"));
				});

			var result1 = block1.ReceiveAsync();
			var result2 = block2.ReceiveAsync();
			Task.WhenAny(result1, result2).Wait();

			if (result1.IsCompleted)
			{
				Console.WriteLine("block 1 completed: " + result1.Result);
			}
			else
			{
				Console.WriteLine("block 2 completed: " + result2.Result);
			}
		}
	}
}
